package cn.edu.scau.cmi.zhangjunming.hibernate.DAO;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.zhangjunming.hibernate.domain.Student;

public class StudentDAO {

	private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	private Session session;
	private Transaction transaction;
	
	@SuppressWarnings("deprecation")
	private void setSession() {
		this.session = new Configuration().configure().buildSessionFactory().openSession();
	}
	
	public void save(Student student) {
		try {
			setSession();
			transaction = session.beginTransaction();
			session.save(student);
			transaction.commit();
			session.flush();
			session.close();
			System.out.println("已保存");
		}catch(RuntimeException re) {
			System.out.println(re.toString());
			throw(re);
		}
	}
	
	public void delete(Student student) {
		try {
			setSession();
			transaction = session.beginTransaction();
			session.delete(student);
			transaction.commit();
			session.flush();
			session.close();
			System.out.println("已删除");
		}catch(RuntimeException re) {
			//System.out.println(re.toString());
			throw(re);
		}
	}
	
	public void update(Student student) {
		try {
		    setSession();
		    transaction = session.beginTransaction();
		    session.update(student);
			transaction.commit();
		    session.flush();
		    session.close();
		    System.out.println("已修改");
		}catch(RuntimeException re) {
			//System.out.println(re.toString());
			throw(re);
		}
	}
	
	public List<Student> listAll(){
		try {
			setSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery("from Student");
			List<Student> list = (List<Student>)query.list();
			transaction.commit();
			session.flush();
			session.close();
		    return list;
		}catch(RuntimeException re) {
			//System.out.println(re.toString());
			//return null;
			throw(re);
		}	
	}
	
	public boolean sameId(long n) {
		List<Student> list =  listAll();
		for(int i=0;i<list.size();i++) {
			Student student = list.get(i);
			if(student.getId()==n) {
				return true;
			}
		}
		return false;
	}
}
